﻿using Newtonsoft.Json;
using System.Diagnostics;

namespace CloudPointImportAndExport.Helper
{
    /// <summary>
    /// 基于Newtonsoft.Json类封装的Json处理类
    /// </summary>
    public class JsonHelper
    {
        // 序列化对象的方法
        public static string Serialize<T>(T obj)
        {
            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All,
            };

            string json = JsonConvert.SerializeObject(obj, settings);

            return json;
        }

        // 反序列化对象的方法
        public static T Deserialize<T>(string jsonString)
        {
            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All,
            };


            return JsonConvert.DeserializeObject<T>(jsonString, settings);
        }

        // 导出到文件，带错误处理
        public static void ExportToFile<T>(T obj, string filePath)
        {
            try
            {
                string jsonString = Serialize(obj);
                File.WriteAllText(filePath, jsonString);
                Trace.WriteLine($"数据已成功导出到文件：{filePath}");
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"导出文件时发生错误: {ex.Message}");
            }
        }

        // 从文件导入数据，带错误处理
        public static T ImportFromFile<T>(string filePath)
        {
            try
            {
                
                string jsonString = File.ReadAllText(filePath);
                return Deserialize<T>(jsonString);
            }
            catch (FileNotFoundException ex)
            {
                Trace.WriteLine($"文件未找到: {ex.Message}");
                return default;
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"导入文件时发生错误: {ex.Message}");
                return default;
            }
        }
    }
}
